-- DROP SCHEMA platform;

CREATE SCHEMA platform AUTHORIZATION postgres;

-- DROP TYPE platform."APIKeyPermission";

CREATE TYPE platform."APIKeyPermission" AS ENUM (
	'EXECUTE_GRAPH',
	'READ_GRAPH',
	'EXECUTE_BLOCK',
	'READ_BLOCK');

-- DROP TYPE platform."APIKeyStatus";

CREATE TYPE platform."APIKeyStatus" AS ENUM (
	'ACTIVE',
	'REVOKED',
	'SUSPENDED');

-- DROP TYPE platform."AgentExecutionStatus";

CREATE TYPE platform."AgentExecutionStatus" AS ENUM (
	'INCOMPLETE',
	'QUEUED',
	'RUNNING',
	'COMPLETED',
	'FAILED');

-- DROP TYPE platform."UserBlockCreditType";

CREATE TYPE platform."UserBlockCreditType" AS ENUM (
	'TOP_UP',
	'USAGE');
-- platform."AgentBlock" definition

-- Drop table

-- DROP TABLE platform."AgentBlock";

CREATE TABLE platform."AgentBlock" (
	id text NOT NULL,
	"name" text NOT NULL,
	"inputSchema" text NOT NULL,
	"outputSchema" text NOT NULL,
	CONSTRAINT "AgentBlock_pkey" PRIMARY KEY (id)
);
CREATE UNIQUE INDEX "AgentBlock_name_key" ON platform."AgentBlock" USING btree (name);


-- platform."User" definition

-- Drop table

-- DROP TABLE platform."User";

CREATE TABLE platform."User" (
	id text NOT NULL,
	email text NOT NULL,
	"name" text NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"updatedAt" timestamp(3) NOT NULL,
	metadata jsonb DEFAULT '{}'::jsonb NOT NULL,
	integrations text DEFAULT ''::text NOT NULL,
	CONSTRAINT "User_pkey" PRIMARY KEY (id)
);
CREATE INDEX "User_email_idx" ON platform."User" USING btree (email);
CREATE UNIQUE INDEX "User_email_key" ON platform."User" USING btree (email);
CREATE INDEX "User_id_idx" ON platform."User" USING btree (id);


-- platform."_prisma_migrations" definition

-- Drop table

-- DROP TABLE platform."_prisma_migrations";

CREATE TABLE platform."_prisma_migrations" (
	id varchar(36) NOT NULL,
	checksum varchar(64) NOT NULL,
	finished_at timestamptz NULL,
	migration_name varchar(255) NOT NULL,
	logs text NULL,
	rolled_back_at timestamptz NULL,
	started_at timestamptz DEFAULT now() NOT NULL,
	applied_steps_count int4 DEFAULT 0 NOT NULL,
	CONSTRAINT "_prisma_migrations_pkey" PRIMARY KEY (id)
);


-- platform.apscheduler_jobs definition

-- Drop table

-- DROP TABLE platform.apscheduler_jobs;

CREATE TABLE platform.apscheduler_jobs (
	id varchar(191) NOT NULL,
	next_run_time float8 NULL,
	job_state bytea NOT NULL,
	CONSTRAINT apscheduler_jobs_pkey PRIMARY KEY (id)
);
CREATE INDEX ix_platform_apscheduler_jobs_next_run_time ON platform.apscheduler_jobs USING btree (next_run_time);


-- platform."APIKey" definition

-- Drop table

-- DROP TABLE platform."APIKey";

CREATE TABLE platform."APIKey" (
	id text NOT NULL,
	"name" text NOT NULL,
	prefix text NOT NULL,
	postfix text NOT NULL,
	"key" text NOT NULL,
	status platform."APIKeyStatus" DEFAULT 'ACTIVE'::platform."APIKeyStatus" NOT NULL,
	permissions platform."_APIKeyPermission" NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"lastUsedAt" timestamp(3) NULL,
	"revokedAt" timestamp(3) NULL,
	description text NULL,
	"userId" text NOT NULL,
	CONSTRAINT "APIKey_pkey" PRIMARY KEY (id),
	CONSTRAINT "APIKey_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX "APIKey_key_idx" ON platform."APIKey" USING btree (key);
CREATE UNIQUE INDEX "APIKey_key_key" ON platform."APIKey" USING btree (key);
CREATE INDEX "APIKey_prefix_idx" ON platform."APIKey" USING btree (prefix);
CREATE INDEX "APIKey_status_idx" ON platform."APIKey" USING btree (status);
CREATE INDEX "APIKey_userId_idx" ON platform."APIKey" USING btree ("userId");
CREATE INDEX "APIKey_userId_status_idx" ON platform."APIKey" USING btree ("userId", status);


-- platform."AgentGraph" definition

-- Drop table

-- DROP TABLE platform."AgentGraph";

CREATE TABLE platform."AgentGraph" (
	id text NOT NULL,
	"version" int4 DEFAULT 1 NOT NULL,
	"name" text NULL,
	description text NULL,
	"isActive" bool DEFAULT true NOT NULL,
	"isTemplate" bool DEFAULT false NOT NULL,
	"userId" text NOT NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"updatedAt" timestamp(3) NULL,
	CONSTRAINT "AgentGraph_pkey" PRIMARY KEY (id, version),
	CONSTRAINT "AgentGraph_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);


-- platform."AgentGraphExecution" definition

-- Drop table

-- DROP TABLE platform."AgentGraphExecution";

CREATE TABLE platform."AgentGraphExecution" (
	id text NOT NULL,
	"agentGraphId" text NOT NULL,
	"agentGraphVersion" int4 DEFAULT 1 NOT NULL,
	"userId" text NOT NULL,
	stats text NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"updatedAt" timestamp(3) NULL,
	"executionStatus" platform."AgentExecutionStatus" DEFAULT 'COMPLETED'::platform."AgentExecutionStatus" NOT NULL,
	"startedAt" timestamp(3) NULL,
	CONSTRAINT "AgentGraphExecution_pkey" PRIMARY KEY (id),
	CONSTRAINT "AgentGraphExecution_agentGraphId_agentGraphVersion_fkey" FOREIGN KEY ("agentGraphId","agentGraphVersion") REFERENCES platform."AgentGraph"(id,"version") ON DELETE CASCADE ON UPDATE CASCADE,
	CONSTRAINT "AgentGraphExecution_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);


-- platform."AnalyticsDetails" definition

-- Drop table

-- DROP TABLE platform."AnalyticsDetails";

CREATE TABLE platform."AnalyticsDetails" (
	id text DEFAULT gen_random_uuid() NOT NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"updatedAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"userId" text NOT NULL,
	"type" text NOT NULL,
	"data" jsonb NULL,
	"dataIndex" text NULL,
	CONSTRAINT "AnalyticsDetails_pkey" PRIMARY KEY (id),
	CONSTRAINT "AnalyticsDetails_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX "AnalyticsDetails_type_idx" ON platform."AnalyticsDetails" USING btree (type);
CREATE INDEX "analyticsDetails" ON platform."AnalyticsDetails" USING btree ("userId", type);


-- platform."AnalyticsMetrics" definition

-- Drop table

-- DROP TABLE platform."AnalyticsMetrics";

CREATE TABLE platform."AnalyticsMetrics" (
	id text DEFAULT gen_random_uuid() NOT NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"updatedAt" timestamp(3) NOT NULL,
	"analyticMetric" text NOT NULL,
	value float8 NOT NULL,
	"dataString" text NULL,
	"userId" text NOT NULL,
	CONSTRAINT "AnalyticsMetrics_pkey" PRIMARY KEY (id),
	CONSTRAINT "AnalyticsMetrics_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);


-- platform."IntegrationWebhook" definition

-- Drop table

-- DROP TABLE platform."IntegrationWebhook";

CREATE TABLE platform."IntegrationWebhook" (
	id text NOT NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"updatedAt" timestamp(3) NULL,
	"userId" text NOT NULL,
	provider text NOT NULL,
	"credentialsId" text NOT NULL,
	"webhookType" text NOT NULL,
	resource text NOT NULL,
	events _text NULL,
	config jsonb NOT NULL,
	secret text NOT NULL,
	"providerWebhookId" text NOT NULL,
	CONSTRAINT "IntegrationWebhook_pkey" PRIMARY KEY (id),
	CONSTRAINT "IntegrationWebhook_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE RESTRICT ON UPDATE CASCADE
);


-- platform."UserBlockCredit" definition

-- Drop table

-- DROP TABLE platform."UserBlockCredit";

CREATE TABLE platform."UserBlockCredit" (
	"transactionKey" text NOT NULL,
	"createdAt" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"userId" text NOT NULL,
	"blockId" text NULL,
	amount int4 NOT NULL,
	"type" platform."UserBlockCreditType" NOT NULL,
	"isActive" bool DEFAULT true NOT NULL,
	metadata jsonb NULL,
	CONSTRAINT "UserBlockCredit_pkey" PRIMARY KEY ("transactionKey", "userId"),
	CONSTRAINT "UserBlockCredit_blockId_fkey" FOREIGN KEY ("blockId") REFERENCES platform."AgentBlock"(id) ON DELETE SET NULL ON UPDATE CASCADE,
	CONSTRAINT "UserBlockCredit_userId_fkey" FOREIGN KEY ("userId") REFERENCES platform."User"(id) ON DELETE CASCADE ON UPDATE CASCADE
);


-- platform."AgentNode" definition

-- Drop table

-- DROP TABLE platform."AgentNode";

CREATE TABLE platform."AgentNode" (
	id text NOT NULL,
	"agentBlockId" text NOT NULL,
	"agentGraphId" text NOT NULL,
	"agentGraphVersion" int4 DEFAULT 1 NOT NULL,
	"constantInput" text DEFAULT '{}'::text NOT NULL,
	metadata text DEFAULT '{}'::text NOT NULL,
	"webhookId" text NULL,
	CONSTRAINT "AgentNode_pkey" PRIMARY KEY (id),
	CONSTRAINT "AgentNode_agentBlockId_fkey" FOREIGN KEY ("agentBlockId") REFERENCES platform."AgentBlock"(id) ON DELETE RESTRICT ON UPDATE CASCADE,
	CONSTRAINT "AgentNode_agentGraphId_agentGraphVersion_fkey" FOREIGN KEY ("agentGraphId","agentGraphVersion") REFERENCES platform."AgentGraph"(id,"version") ON DELETE CASCADE ON UPDATE CASCADE,
	CONSTRAINT "AgentNode_webhookId_fkey" FOREIGN KEY ("webhookId") REFERENCES platform."IntegrationWebhook"(id) ON DELETE SET NULL ON UPDATE CASCADE
);


-- platform."AgentNodeExecution" definition

-- Drop table

-- DROP TABLE platform."AgentNodeExecution";

CREATE TABLE platform."AgentNodeExecution" (
	id text NOT NULL,
	"agentGraphExecutionId" text NOT NULL,
	"agentNodeId" text NOT NULL,
	"addedTime" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"queuedTime" timestamp(3) NULL,
	"startedTime" timestamp(3) NULL,
	"endedTime" timestamp(3) NULL,
	"executionData" text NULL,
	stats text NULL,
	"executionStatus" platform."AgentExecutionStatus" DEFAULT 'COMPLETED'::platform."AgentExecutionStatus" NOT NULL,
	CONSTRAINT "AgentNodeExecution_pkey" PRIMARY KEY (id),
	CONSTRAINT "AgentNodeExecution_agentGraphExecutionId_fkey" FOREIGN KEY ("agentGraphExecutionId") REFERENCES platform."AgentGraphExecution"(id) ON DELETE CASCADE ON UPDATE CASCADE,
	CONSTRAINT "AgentNodeExecution_agentNodeId_fkey" FOREIGN KEY ("agentNodeId") REFERENCES platform."AgentNode"(id) ON DELETE CASCADE ON UPDATE CASCADE
);


-- platform."AgentNodeExecutionInputOutput" definition

-- Drop table

-- DROP TABLE platform."AgentNodeExecutionInputOutput";

CREATE TABLE platform."AgentNodeExecutionInputOutput" (
	id text NOT NULL,
	"name" text NOT NULL,
	"data" text NOT NULL,
	"time" timestamp(3) DEFAULT CURRENT_TIMESTAMP NOT NULL,
	"referencedByInputExecId" text NULL,
	"referencedByOutputExecId" text NULL,
	CONSTRAINT "AgentNodeExecutionInputOutput_pkey" PRIMARY KEY (id),
	CONSTRAINT "AgentNodeExecutionInputOutput_referencedByInputExecId_fkey" FOREIGN KEY ("referencedByInputExecId") REFERENCES platform."AgentNodeExecution"(id) ON DELETE CASCADE ON UPDATE CASCADE,
	CONSTRAINT "AgentNodeExecutionInputOutput_referencedByOutputExecId_fkey" FOREIGN KEY ("referencedByOutputExecId") REFERENCES platform."AgentNodeExecution"(id) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE UNIQUE INDEX "AgentNodeExecutionInputOutput_referencedByInputExecId_refer_key" ON platform."AgentNodeExecutionInputOutput" USING btree ("referencedByInputExecId", "referencedByOutputExecId", name);


-- platform."AgentNodeLink" definition

-- Drop table

-- DROP TABLE platform."AgentNodeLink";

CREATE TABLE platform."AgentNodeLink" (
	id text NOT NULL,
	"agentNodeSourceId" text NOT NULL,
	"sourceName" text NOT NULL,
	"agentNodeSinkId" text NOT NULL,
	"sinkName" text NOT NULL,
	"isStatic" bool DEFAULT false NOT NULL,
	CONSTRAINT "AgentNodeLink_pkey" PRIMARY KEY (id),
	CONSTRAINT "AgentNodeLink_agentNodeSinkId_fkey" FOREIGN KEY ("agentNodeSinkId") REFERENCES platform."AgentNode"(id) ON DELETE CASCADE ON UPDATE CASCADE,
	CONSTRAINT "AgentNodeLink_agentNodeSourceId_fkey" FOREIGN KEY ("agentNodeSourceId") REFERENCES platform."AgentNode"(id) ON DELETE CASCADE ON UPDATE CASCADE
);



-- DROP FUNCTION platform.add_user_to_platform();

CREATE OR REPLACE FUNCTION platform.add_user_to_platform()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
BEGIN
    INSERT INTO platform."User" (id, email, "updatedAt")
    VALUES (NEW.id, NEW.email, now());
    RETURN NEW;
END;
$function$
;
